﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Isotop.Text
{
	public static class IEnumerableExtensions
	{
		public static double Median(this IEnumerable<long> source)
		{
			return Median(source.Select(l => (double)l));
		}

		public static double Median(this IEnumerable<int> source)
		{
			return Median(source.Select(l => (double)l));
		}

		public static double Median(this IEnumerable<double> source)
		{
			if (source.Count() == 0)
				throw new InvalidOperationException("Cannot compute median for an empty set.");

			var sortedList = (from number in source
									orderby number
									select number).ToList();

			int index = sortedList.Count / 2;

			if (sortedList.Count % 2 == 0) // Even number of items.
				return (sortedList[index] + sortedList[index - 1]) / 2;

			// Odd number of items.
			return sortedList[index];
		}
	}
}
